<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员个人信息</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
    <link rel="stylesheet" href="../css/admin.css">
</head>
<script>
    function goToIndex(){
        window.location.href = '../index.jsp'
    }
    function goToAdminInfo(){
        window.location.href = 'admin.jsp'
    }
</script>
<body>
<%
    String defaultUrl = "https://tse2-mm.cn.bing.net/th/id/OIP-C.j57souiFOvYA0LUiw-2BkAHaHa?rs=1&pid=ImgDetMain";
    HttpSession session1 = request.getSession();
    String adminUsername = (String) session1.getAttribute("adminUsername");
    String adminAvatarUrl = (String) session.getAttribute("adminAvatarUrl");

    Integer userIdInt = (Integer) session.getAttribute("adminId");
    String admin_id = userIdInt != null ? userIdInt.toString() : "未知";
%>
<div class="header">
    <p>欢迎，<%= adminUsername %></p>
    <div>
        <img src="<%= (adminAvatarUrl != null && !adminAvatarUrl.isEmpty()) ? adminAvatarUrl : defaultUrl %>"
             alt="头像"
             id="adminAvatar"
             style="width: 50px; height: 50px; border-radius: 50%;"
             onerror="this.src='<%= defaultUrl %>'"
        >
        <button onclick="logout()">退出登录</button>
        <button onclick="goToIndex()" style="z-index: 1000">回到首页</button>
    </div>
</div>

<div class="container">
    <div class="main-content">
        <div class="card">
            <h2>个人信息管理</h2>
            <div class="avatar-section">
                <h3>更改头像</h3>
                <form id="avatarForm" enctype="multipart/form-data">
                    <input type="file" name="avatar" accept="image/*" required>
                    <button type="submit">上传头像</button>
                </form>
                <div id="avatarMessage" class="message"></div>
            </div>
            
            <div class="password-section">
                <h3>修改密码</h3>
                <form id="passwordForm">
                    <div class="form-group">
                        <label for="oldPassword">原密码:</label>
                        <input type="password" id="oldPassword" required>
                    </div>
                    <div class="form-group">
                        <label for="newPassword">新密码:</label>
                        <input type="password" id="newPassword" required>
                    </div>
                    <button type="submit">修改密码</button>
                </form>
                <div id="passwordMessage" class="message"></div>
            </div>

            <div class="profile-section">
                <h3>修改个人信息</h3>
                <form id="profileForm">
                    <div class="form-group">
                        <label for="newUsername">用户名:</label>
                        <input type="text" id="newUsername" name="newUsername" value="<%= adminUsername %>" required>
                    </div>
                    <div class="form-group">
                        <label for="email">邮箱:</label>
                        <input type="email" id="email" name="email" value="<%= session.getAttribute("adminEmail") %>" required>
                    </div>
                    <button type="submit">保存修改</button>
                </form>
                <div id="profileMessage" class="message"></div>
            </div>
        </div>
    </div>
</div>

<script>
    // 上传头像
    document.getElementById('avatarForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const formData = new FormData(this);
        formData.append('action', 'updateAvatar');

        fetch('adminInfoServlet', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            const message = document.getElementById('avatarMessage');
            if (result.status === 'success') {
                document.getElementById('adminAvatar').src = result.avatarUrl;
                message.textContent = '头像上传成功！';
                message.style.color = 'green';
            } else {
                message.textContent = '上传失败：' + result.message;
                message.style.color = 'red';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('avatarMessage').textContent = '网络错误，请稍后重试';
        });
    });

    // 修改密码
    document.getElementById('passwordForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const oldPassword = document.getElementById('oldPassword').value;
        const newPassword = document.getElementById('newPassword').value;

        fetch('adminInfoServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=updatePassword&oldPassword=${oldPassword}&newPassword=${newPassword}`
        })
        .then(response => response.json())
        .then(result => {
            const message = document.getElementById('passwordMessage');
            if (result.status === 'success') {
                message.textContent = '密码修改成功！';
                message.style.color = 'green';
            } else {
                message.textContent = '修改失败：' + result.message;
                message.style.color = 'red';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('passwordMessage').textContent = '网络错误，请稍后重试';
        });
    });

    // 更新个人信息
    document.getElementById('profileForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const formData = new FormData(this);
        formData.append('action', 'updateProfile');

        fetch('adminInfoServlet', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            const message = document.getElementById('profileMessage');
            if (result.status === 'success') {
                message.textContent = '个人信息更新成功！';
                message.style.color = 'green';
                // 更新页面显示的用户名
                document.querySelector('.header p').textContent = '欢迎，' + formData.get('newUsername');
            } else {
                message.textContent = '更新失败：' + result.message;
                message.style.color = 'red';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('profileMessage').textContent = '网络错误，请稍后重试';
        });
    });

    // 退出登录
    function logout() {
        fetch('adminInfoServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=logout'
        }).then(response => {
            if(response.ok) {
                session1.invalidate();
                window.location.href = '../index.jsp';
            }
        });
    }
</script>

<style>
.profile-section {
    margin-top: 20px;
    padding: 20px;
    border-top: 1px solid #eee;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
}

.form-group input {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.message {
    margin-top: 10px;
    padding: 10px;
    border-radius: 4px;
}
</style>
</body>
</html>
